<template>
  <CrudTable
    :buttons="tableButtons"
    row-selection-type="multiple"
    :columns="tableColumns"
    @currentChange="handleSelectChange"
    :tableData="pageData.tableData.records"
    :loading="pageData.loading"
    :pagination="pageData.pagination"
    @pageChange="handlePageChange"
    @rowDbClick="handleRowDbClick"
    :showRefresh="true"
    :showExport="false"
    @refreshData="handleTableRefresh"
  >
    <template #operations>
      <InputSelect
        placeholder="点击右侧按钮选择客户筛选"
        @onClick="pageData.customer.show = true"
        :value="pageData.filterValue.customerMainName"
      />
      <t-input placeholder="输入订单号进行搜索" v-model="pageData.filterValue.orderId" />
      <t-input placeholder="输入订单名称进行搜索" v-model="pageData.filterValue.orderName" />
      <t-input placeholder="输入发票号进行搜索" v-model="pageData.filterValue.ticketId" />
      <t-space size="small">
        <t-button theme="primary" @click="filterChange">查询</t-button>
        <t-button theme="warning" @click="handleFilterReset">重置</t-button>
      </t-space>
    </template>
    <template #rowOperations="{ row }">
      <div class="crud-table__row_operations">
        <t-link variant="text" theme="primary" @click="handleOperateRow('view', row)">查看</t-link>
        <t-link variant="text" theme="primary" @click="handleOperateRow('edit', row)">修改</t-link>
        <t-link variant="text" theme="danger" @click="handleOperateRow('delete', row)">删除</t-link>
      </div>
    </template>
  </CrudTable>

  <EditForm
    v-if="pageData.showEditForm"
    :dialogVisible="pageData.showEditForm"
    :mode="pageData.editFormMode"
    :id="pageData.selectedRowId"
    :statusDict="pageData.statusDict"
    @close="handleDialogClose"
  />

  <SelectTable
    v-if="pageData.customer.show"
    :loading="pageData.customer.loading"
    :showDialog="pageData.customer.show"
    title="选择客户"
    width="60vw"
    rowSelectionType="single"
    :tableData="pageData.customer.data.records"
    :columns="customerColumns"
    @onConfirm="handleCustomerConfirm"
    @onCancel="handleCustomerClose"
    :pagination="pageData.customer.pagination"
    :filter-value="pageData.customer.filterValue"
    @filter-change="handleCustomerFilterChange"
    @page-change="handleCustomerPageChange"
  />
</template>

<script lang="tsx" setup>
// 框架和组件库
import { computed, reactive, defineAsyncComponent } from "vue";
import { DialogPlugin, MessagePlugin } from "tdesign-vue-next";

// TS 类型文件
import type { ICrudTableDataPage, ISelectDataType, ISelectTableGroups, TFilterValue } from "@/types";

// 工具函数
import { http } from "@/utils/fetch";

// 常量
import { PAGINATION_VALUE } from "@/common/constants";

// API
import { getCustomerList } from "@/api/cas";

// 业务数据
import { tableColumns } from "./components/columns";
import { tableColumns as customerColumns } from "@/pages/Dashboard/CAS/Customer/components/columns";

// 动态组件
const EditForm = defineAsyncComponent(() => import("./components/EditForm.vue"));

const GET_LIST_PATH = "/express/findAll"; // 查询信息接口
const DELETE_ITEM_PATH = "/express/delete"; // 删除接口

const pageData = reactive({
  loading: false,
  tableData: {} as ICrudTableDataPage,
  selectedRow: {},
  selectedRowId: "",
  selectedRowsEvent: {} as Record<string, any>,
  showEditForm: false,
  editFormMode: "",
  filterValue: {
    customerMainName: "",
    customerId: "",
    orderNo: "",
    orderName: "",
    ticketId: ""
  } as TFilterValue,
  pagination: {
    pageSize: 20,
    total: 0,
    current: 1
  },
  customer: {
    show: false,
    data: {},
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    },
    filterValue: {}
  } as ISelectTableGroups,
  statusDict: [] as ISelectDataType[],
  exchangeRateData: {} as Record<string, any>
});

// 表格操作按钮配置
const tableButtons = computed(() => [
  {
    name: "新增",
    click: () => {
      handleOperateRow("new");
    }
  }
]);

// 表格列配置

// 获取列表数据
const findAllList = async () => {
  pageData.loading = true;
  const resultData = await http(
    "POST",
    `${GET_LIST_PATH}?currentPage=${pageData.pagination.current}&pageSize=${pageData.pagination.pageSize}`,
    pageData.filterValue
  );
  if (resultData.code === 200) {
    pageData.tableData = resultData.data;
    pageData.pagination.total = resultData.data.total;
    pageData.pagination.current = resultData.data.current;
    pageData.pagination.pageSize = resultData.data.size;
    pageData.loading = false;
  }
};

const handlePageChange = (pageInfo: Record<string, any>) => {
  pageData.pagination.pageSize = pageInfo.pageSize;
  pageData.pagination.current = pageInfo.current;
  findAllList();
};

const getCustomerData = async () => {
  pageData.customer.loading = true;
  const resultData = await getCustomerList(
    pageData.pagination.current,
    pageData.pagination.pageSize,
    pageData.filterValue
  );

  if (resultData.code === 200) {
    pageData.customer.data = resultData.data;
    pageData.customer.pagination.total = resultData.data.total;
    pageData.customer.pagination.current = resultData.data.current;
    pageData.customer.pagination.pageSize = resultData.data.size;
    pageData.customer.loading = false;
  }
};

const handleCustomerPageChange = (pageInfo: Record<string, any>) => {
  pageData.customer.pagination.pageSize = pageInfo.pageSize;
  pageData.customer.pagination.current = pageInfo.current;
  getCustomerData();
};

const handleCustomerFilterChange = (filters: Record<string, any>) => {
  pageData.filterValue = filters;
  pageData.customer.pagination = structuredClone(PAGINATION_VALUE);
  getCustomerData();
};

const handleCustomerConfirm = (e: Record<string, any>) => {
  pageData.filterValue.customerId = e.options.currentRowData.id;
  pageData.filterValue.customerMainName = e.options.currentRowData.name;
  pageData.customer.show = false;
};

// const handleCustomerRefresh = () => {
//   pageData.customer.filterValue = {};
//   pageData.customer.pagination = structuredClone(PAGINATION_VALUE);
//   getCustomerData();
// };

const handleCustomerClose = () => {
  pageData.customer.show = false;
};

// 过滤事件触发函数
const filterChange = () => {
  pageData.pagination = structuredClone(PAGINATION_VALUE);
  findAllList();
};

const handleFilterReset = () => {
  pageData.pagination = structuredClone(PAGINATION_VALUE);
  pageData.filterValue = { customerMainName: "", customerId: "", orderNo: "", orderName: "", ticketId: "" };
  findAllList();
};

const handleTableRefresh = () => {
  pageData.selectedRow = {};
  pageData.selectedRowId = "";
  pageData.pagination = structuredClone(PAGINATION_VALUE);
  pageData.filterValue = { customerMainName: "", customerId: "", orderNo: "", orderName: "", ticketId: "" };
  findAllList();
  getCustomerData();
};

const handleRowDbClick = (context: Record<string, any>) => {
  handleOperateRow("view", context.row);
};

const handleOperateRow = (mode: string, row?: Record<string, any>) => {
  if (mode !== "delete") {
    if (mode === "new") {
      pageData.selectedRow = {};
      pageData.selectedRowId = "";
    } else {
      pageData.selectedRow = row!;
      pageData.selectedRowId = row!.id;
    }
    pageData.editFormMode = mode;
    pageData.showEditForm = true;
  } else if (mode === "delete") {
    const confirmDialog = DialogPlugin({
      header: "警告",
      body: "确定要删除这一条数据吗？",
      confirmBtn: "确定",
      cancelBtn: "取消",
      theme: "warning",
      onConfirm: async () => {
        const deleteData = await http("DELETE", `${DELETE_ITEM_PATH}?id=${row!.id}`);
        if (deleteData.code === 200) {
          MessagePlugin.success("删除成功！");
          findAllList();
          confirmDialog.hide();
        }
      },
      onClose: () => {
        confirmDialog.hide();
      }
    });
  } else {
    MessagePlugin.error("错误：未知的表格操作模式。");
  }
};

const handleSelectChange = (e: Record<string, any>) => {
  pageData.selectedRowsEvent = e;
};

// 对话框关闭时的处理函数
const handleDialogClose = (e: string) => {
  if (e === "success") {
    MessagePlugin.success("操作成功！");
    findAllList();
  }
  pageData.showEditForm = false;
};

findAllList();
getCustomerData();
// getExchangeRate();
</script>
